package com.smartwebx.fr.util;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.google.common.base.Enums;
import com.google.common.base.Optional;
import com.smartwebx.fr.dao.ExecDao;
import com.smartwebx.fr.dao.GetJdbcTempalte;
import com.smartwebx.fr.util.StationFinalFields.DataSources;

/**
 * 数据访问工具类
 * 
 * @author XX
 * 
 */
@Repository
public class DataAccessTool {
	@Autowired
	private GetJdbcTempalte getJdbcTempalte;
	@Autowired
	private ExecDao execDao;

	/**
	 * 
	 * @param code
	 * @param dbType
	 * @return
	 */
	public List<List<String>> getDataNotParam(String code, String dbType) {
		return getData(code, null, dbType, true);
	}

	public String getDataTextNotParam(String code, String dbType) {
		List<List<String>> result = getData(code, null, dbType, false);
		String backTxt = null;
		if (!result.isEmpty()) {
			List<String> childResult = result.get(0);
			if (!childResult.isEmpty()) {
				backTxt = childResult.get(0);
			}
		}
		return backTxt;
	}

	public List<List<String>> getDataAndParam(String code,
			List<String> paramList, String dbType) {
		return getData(code, paramList, dbType, true);
	}

	private List<List<String>> getData(String code, List<String> paramList,
			String dbName, Boolean hasHeader) {
		Optional<DataSources> dataSourceKey = Enums.getIfPresent(
				DataSources.class, dbName);
		DataSources ds = null;
		if (dataSourceKey.isPresent()) {
			ds = dataSourceKey.get();
		} else {
			new Exception("没有匹配数据源");
		}
		JdbcTemplate jdbcTemplate = getJdbcTempalte.getJdbcTemplate(ds);

		return execDao.getResultByParam(code, paramList, jdbcTemplate,
				hasHeader);
	}
}
